import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChange } from '@angular/core';
import { FormGroup, FormBuilder, Validators }        from '@angular/forms';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import { CwsValidators } from '../cws-validators/cws-validators';
import { ToasterService} from 'angular2-toaster';
import { TranslateService } from '@ngx-translate/core';
import { AuthService } from '../auth/auth.service';
import { ControlToasterService } from '../control-toaster/control-toaster.service';

@Component({
  moduleId: module.id,
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit, OnChanges {

  @Input() email:string = '';
  @Input() form:FormGroup;

  @Output() logined: EventEmitter<{token: string}> = new EventEmitter();

  constructor(
    private fb: FormBuilder,
    private translate: TranslateService,
    private toaster: ToasterService,
    private auth: AuthService,
    private controlToaster: ControlToasterService
  ) { }

  ngOnInit() {
    this.initForm(this.email);
  }

  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
    try{
      this.form.patchValue({email: changes.email.currentValue});
    }catch(ex){
      // 第一次调用，在ngOnInit之前，form还没初始化
    }
  }

  signIn () {
    this.auth.signIn(this.formatForm(this.form.value))
    .subscribe(
      data => this.logined.emit(data),
      error => this.showError(error)
    );
  }

  private showError (error) {
    if (error.status !== -1) {
      return this.controlToaster.popKnownError(error);
    }
    let message = error.message;
    switch (message) {
      case 401:
        message = 'WrongPasswordTip';
        break;
      case 404:
        message = 'AccountNotExistTip';
        break;
    }
    this.controlToaster.popWarning(error.message);
  }

  private initForm (email = '') {
    this.form = this.fb.group({
      email: [email,
        [
          Validators.required,
          CwsValidators.email,
        ]
      ],
      password: ['',
        [
          Validators.required
        ]
      ],
      rememberMe: false
    });
  }

  private formatForm (form) {
    return {
      email: form.email,
      password: form.password,
      rememberMe: +form.rememberMe
    }
  }
}
